package com.stu.exercise.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stu.exercise.entity.R;
import com.stu.exercise.entity.User;
import com.stu.exercise.mapper.LoginMapper;
import com.stu.exercise.service.LoginService;
import com.stu.exercise.utils.BCryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, User> implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Override
    public R login(User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        User login = loginMapper.selectOne(wrapper);
        if (login == null){
            return R.error(500, "用户名错误");
        }
        if (!BCryptUtil.matches(user.getPassword(), login.getPassword())){
            return R.error(500, "密码错误");
        }
        return R.success("登录成功", login);
    }

    @Override
    public R reset(User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        User usr = loginMapper.selectOne(wrapper);
        if (usr == null){
            return R.error(500, "用户名不存在");
        }
        usr.setPassword(BCryptUtil.encrypt(user.getPassword()));
        int update = loginMapper.update(usr, null);
        if(update < 1){
            return R.error(500, "修改失败");
        }
        return R.success("修改成功", null);
    }
}
